<?php
declare(strict_types=1);

namespace SixShop\Wechat\Entity;

use app\model\User;
use SixShop\Core\Entity\BaseEntity;
use SixShop\Wechat\ChineseUtil;
use SixShop\Wechat\Service\MiniApp;
use think\facade\Event;

/**
 * @mixin \SixShop\Wechat\Model\ExtensionWechatUserModel
 */
class ExtensionWechatUserEntity extends BaseEntity
{

    public function getUserID(string $code, string $appID = null): int
    {
        $miniApp = app()->make(MiniApp::class, [$appID]);
        $utils = $miniApp->getUtils();
        $response = $utils->codeToSession($code);
        $appID = $miniApp->getConfig()->get('app_id');
        $wechatUser = $this->where([
            'openid' => $response['openid'],
            'appid' => $appID
        ])->findOrEmpty();
        if ($wechatUser->isEmpty()) {
            $wechatUser->openid = $response['openid'];
            $wechatUser->appid = $appID;
            $wechatUser->nickname = '匿名用户';
            $wechatUser->user_id = $this->createNewUser();
        }
        $wechatUser->save(['session_key' => $response['session_key']]);

        return $wechatUser->user_id;
    }

    private function createNewUser(): int
    {
        $timestamp = time();
        $randomStr = bin2hex(random_bytes(3));
        $user = new User();
        $user->username = "wx_{$timestamp}_{$randomStr}";
        $user->nickname = ChineseUtil::randomChineseName();
        Event::trigger('beforeCreateUser', [$user, 'wechat' ]);
        $user->save();
        return $user->id;
    }

    public function getPhoneNumber(string $code)
    {
        $miniApp = app()->make(MiniApp::class);
        $response = $miniApp->getClient()->postJson('/wxa/business/getuserphonenumber', [
            'code' => $code,
        ]);
        $content = $response->getContent();
        $data = json_decode($content, true);
        return $data['phone_info'];
    }
}